package toubiao.interceptors;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import toubiao.domain.vo.assist.SessionInfo;
import toubiao.domain.vo.manage.Resource;
import toubiao.service.ResourceServiceI;
import toubiao.service.init.InitServiceI;
import toubiao.utils.ProUtilConfig;




    /**
    * @ClassName: SecurityInterceptor
    * @Description: 权限拦击, 1,需初始化 排除url 
    * @author 宁少林
    * @date 2016年8月27日
    *
    */
@Component
public class SecurityInterceptor implements HandlerInterceptor , ApplicationListener<ContextRefreshedEvent> {
	

	private static final Logger logger = Logger.getLogger(SecurityInterceptor.class);

	private Set<String> excludeServletPathSet=new HashSet<>();// 不需要拦截的资源
	
	//private int securityInterceptorTimes=1;
	
	
	    /**
	    * @Fields initService : 实验容器加载次数
	    */
	@Autowired
	private InitServiceI initService;
	
	@Autowired
	private ResourceServiceI resourceService;
	
	/**
	 * 完成页面的render后调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception {

	}

	/**
	 * 在调用controller具体方法后拦截
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {
		
	}

	/**
	 * 在调用controller具体方法前拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String requestUri = request.getRequestURI();
		String contextPath = request.getContextPath();
		String url = requestUri.substring(contextPath.length());
		logger.info(url);

		if (url.indexOf("/baseController/") > -1 || excludeServletPathSet.contains(url)) {// 如果要访问的资源是不需要验证的
			return true;
		}

		SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(ProUtilConfig.getSessionInfoName());
		if (sessionInfo == null || sessionInfo.getUserId()==null) {// 如果没有登录或登录超时
			logger.info("用户未登录.");
			request.setAttribute("errorMsg", "您还没有登录或登录已超时，请重新登录，然后再刷新本功能！");
			request.getRequestDispatcher("/WEB-INF/jsp/error/noSession.jsp").forward(request, response);
			return false;
		}

		if (!sessionInfo.getUrlSet().contains(url)) {// 如果当前用户没有访问此资源的权限
			logger.info("用户无权限.");
			request.setAttribute("errorMsg", "您没有访问此资源的权限！<br/>请联系超管赋予您<br/>[" + url + "]<br/>的资源访问权限！");
			request.getRequestDispatcher("/WEB-INF/jsp/error/noSecurity.jsp").forward(request, response);
			return false;
		}
		logger.info("SecurityInterceptor passed the url :"+ url);
		return true;
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent arg0) {
		// TODO Auto-generated method stub
		//initService.initAll();
		//System.out.println("SecurityInterceptor = " +securityInterceptorTimes++);
		//logger.info("in sercurity application event.");
		//logger.info(resourceService.getResourceByAucType("public").size()+"");
		List<Resource> list=resourceService.getResourceByAucType("public");
		for(Resource r:list){
			if(r!=null && r.getUrl()!=null){
				excludeServletPathSet.add(r.getUrl());
			}
		}
	}
}
